/*
* nsMessagePipe.cpp
*
*  Created on: 2013-3-3
*      Author: lmind
*/

#include "include.h"


/* Implementation file */
NS_IMPL_ISUPPORTS1(nsMessagePipe, nsIMessagePipe);

nsMessagePipe::nsMessagePipe()
{
	AddRef();
	m_receivers.Init();
}

nsMessagePipe::~nsMessagePipe()
{
	
}

/* readonly attribute wstring name; */
NS_IMETHODIMP nsMessagePipe::GetName(PRUnichar * *aName)
{
	*aName = ToNewUnicode(m_name);
	return NS_OK;
}

/* void addReceiver (in wstring title, in nsIMessageReceiver receiver); */
NS_IMETHODIMP nsMessagePipe::AddReceiver(const PRUnichar * title, nsIMessageReceiver *receiver)
{
	nsAutoString key(title);
	key.Length();
	nsCOMArray<nsIMessageReceiver> *pArray = NULL;
	m_receivers.Get(key, &pArray);
	if (!pArray)
	{
		pArray = new nsCOMArray<nsIMessageReceiver>();
		m_receivers.Put(key, pArray);
	}
	pArray->AppendObject(receiver);
	
	return NS_OK;
}

/* void addGlobalReceiver (in nsIMessageReceiver receiver); */
NS_IMETHODIMP nsMessagePipe::AddGlobalReceiver(nsIMessageReceiver *receiver)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

/* void removeReceiver (in wstring title, in nsIMessageReceiver receiver); */
NS_IMETHODIMP nsMessagePipe::RemoveReceiver(const PRUnichar * title, nsIMessageReceiver *receiver)
{
	nsAutoString key(title);
	nsCOMArray<nsIMessageReceiver> *pArray = NULL;
	m_receivers.Get(key, &pArray);
	if (pArray)
	{
		pArray->RemoveObject(receiver);
		if (pArray->Count() == 0)
		{
			m_receivers.Remove(key);
		}
	}
	return NS_OK;
}

/* void removeGlobalReceiver (in wstring title, in nsIMessageReceiver receiver); */
NS_IMETHODIMP nsMessagePipe::RemoveGlobalReceiver(const PRUnichar * title, nsIMessageReceiver *receiver)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

/* void send (in wstring title, in wstring data); */
NS_IMETHODIMP nsMessagePipe::Send(const PRUnichar * title, const PRUnichar * data)
{
	nsCOMArray<nsIMessageReceiver> *pArray = NULL;
	m_receivers.Get(nsAutoString(title), &pArray);

	if (!pArray)
		return NS_OK;

	for (PRInt32 i = 0; i < pArray->Count(); i++)
	{
		nsIMessageReceiver *p = (*pArray)[i];
		nsresult r = p->WriteValue(title, data);
		if (NS_FAILED(r)) {
			return r;
		}
	}

	return NS_OK;
}
